#!/bin/bash

# 测试导出一个没有数据的表：ems_ts.em000000_15min_k201000207
user="root"
pwd="taosdata"
db="ems_ts"
child_table="em000000_15min_k201000207"
filter_sql_part="where ts >= '2023-10-10 00:15:00.000' and ts <= '2023-10-11 00:00:00.000'"
csv_file="/mnt/sdc/opt/ems-archive/test/files/ems_ts_data_em000000_15min_k201000207.csv"

#
# 执行 sql
#
function execute_sql(){
    local sql=$1
    taos -u "$user" "-p$pwd" -s "$sql"
}

#
# 删除多余的信息，用于处理 “TDengine 连接过程” 打印的内容
#
function process_connected(){
    sed '{
        /^failed to create dir/d      # 删除以 "failed to create dir" 开头的行
        /^Welcome to the TDengine/d   # 删除以 "Welcome to the TDengine" 开头的行
        /^Copyright/d                 # 删除以 "Copyright" 开头的行
        /^$/d                         # 删除空行
        /^taos>/d                     # 删除以 "taos>" 开头的行
        /^\r/d                        # 删除紧跟 "taos>" 后的回车符        
        /^Query OK/d                  # 删除以 "Query OK" 开头的行        
    }'    
}

backup_sql="select * from ${db}.${child_table} ${filter_sql_part} order by ts >> '${csv_file}'"

execute_sql "$backup_sql"

if [ ! -f $csv_file ]
then
    echo "WARN: 子表 ${child_table} 没有导出任何数据，请注意核实该情况 [ select count(*) from ${db}.${child_table}; ]"
fi

